﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Meeting.DBUtility;
using Newtonsoft.Json;
using System.Data.SqlClient;
using System.Net;
using System.Configuration;
using System.IO;
using Meeting.Model;

namespace Meeting.BLL
{
    /// <summary>
    /// 模块作者：吴龙波
    /// 模块日期：2010-12-31
    /// 模块功能：操作从OA获取过来的数据
    /// </summary>
    public class Employee
    {
        public string errorString = "";

        #region 电子政务人员管理
        /// <summary>
        ///  请求url获取人员json数据
        /// </summary>
        /// <param name="url">访问地址</param>
        /// <returns></returns>
        public string Get(string roleId)
        {
            string url = ConfigurationManager.AppSettings["OAUserUrl"];
            try
            {
                url = url + "?method=getPersonsByRole&roleId=" + roleId;
                var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
                var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    var responseText = streamReader.ReadToEnd();
                    return responseText;
                }
            }
            catch (Exception e)
            {
                errorString = e.Message;
                return "";
            }
        }

        public string GetOAEmploy(string roleString)
        {
            if (string.IsNullOrEmpty(roleString))
            {
                errorString = "传入的角色id为空";
                return "";
            }
            string[] strs = roleString.Split(';');
            List<OaUser> oaUserList = new List<OaUser>();
            foreach (string str in strs)
            {
                //添加父节点
                OaUser tUser = new OaUser();
                tUser.parent = "0";
                tUser.account = str;
                tUser.name = GetName(str);
                tUser.nodetype = "role";
                tUser.title = "";
                oaUserList.Add(tUser);
                //
                List<OaUser> temp = new List<OaUser>();
                string json = Get(str);
                if (json == "") continue;
                temp = JsonConvert.DeserializeObject<List<OaUser>>(json);
                foreach (OaUser ou in temp)
                {
                    ou.parent = str;
                    ou.nodetype = "user";

                    oaUserList.Add(ou);
                }
            }
            string test = JsonConvert.SerializeObject(oaUserList);
            return test;
        }

        public string GetName(string str)
        {
            string sql = "Select Name From Role Where Id ='" + str + "' ";
            try
            {
                DataSet ds = DbHelperSQL.Query(sql);
                if (ds == null || ds.Tables[0].Rows.Count < 1) return "没有角色名称";
                return ds.Tables[0].Rows[0]["Name"].ToString();
            }
            catch
            {
                return "没有角色名称";
            }
            //switch(str)
            //{
            //    case "1":
            //        return "党组会议";
            //    case "2":
            //        return "办公会议";
            //    case "3":
            //        return "其他会议";
            //    case "4":
            //        return "局领导";
            //    default:
            //        return "";

            //}
        }

        /// <summary>
        /// 向电子政务系统获取所有人员
        /// 按照人员角色获取
        /// </summary>
        /// <returns></returns>
        public string GetOaAllUser()
        {
            JsonResponse response = new JsonResponse();
            try
            {
                //获取系统中所有角色
                string sql = "Select Id,Name From Role Order By Sort";
                DataSet ds = DbHelperSQL.Query(sql);
                if (ds == null || ds.Tables[0].Rows.Count < 1)
                {
                    response.success = false;
                    response.Message = "获取移动办公系统人员数据失败！";
                }
                //遍历角色，获取角色下的人员                
                List<OaUser> resultList = new List<OaUser>();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    string employees = Get(dr["Id"].ToString());
                    if (employees == "") continue;
                    List<OaUser> oas = JsonConvert.DeserializeObject<List<OaUser>>(employees);
                    if (oas == null) continue;
                    oas.ForEach(x => { x.roleId = dr["Id"].ToString(); x.roleName = dr["Name"].ToString(); });
                    resultList.AddRange(oas);
                }

                if (resultList.Count == 0)
                {
                    response.success = false;
                    response.Message = "获取移动办公系统人员数据失败！";
                }
                else
                {
                    response.success = true;
                    response.ResponseData = resultList;
                }
                return JsonConvert.SerializeObject(response);
            }
            catch (Exception ex)
            {
                errorString = ex.Message;
                response.success = false;
                response.Message = errorString;
                return JsonConvert.SerializeObject(response); ;
            }
        }
        #endregion

        #region 本地人员管理
        /// <summary>
        /// 帐号不重复
        /// </summary>
        public bool Exists(string account)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select count(1) from Employee");
            strSql.Append(" where Account=@Account ");
            SqlParameter[] parameters = {
					new SqlParameter("@Account", SqlDbType.NVarChar,128)};
            parameters[0].Value = account;

            return DbHelperSQL.Exists(strSql.ToString(), parameters);
        }

		/// <summary>
		/// 增加一条数据
		/// </summary>
		public bool Add(Meeting.Model.Employee model)
		{
            //判断帐号是否已存在
            if (Exists(model.Account))
            {
                errorString = "已存在该帐号";
                return false;
            }

			StringBuilder strSql=new StringBuilder();
            strSql.Append("insert into Employee(");
            strSql.Append("Account,Name,Title,RoleId,Mobile,PassWord,Comment,RoleName)");
            strSql.Append(" values (");
            strSql.Append("@Account,@Name,@Title,@RoleId,@Mobile,@PassWord,@Comment,@RoleName)");
            SqlParameter[] parameters = {
					new SqlParameter("@Account", SqlDbType.NVarChar,64),
					new SqlParameter("@Name", SqlDbType.NVarChar,64),
					new SqlParameter("@Title", SqlDbType.NVarChar,64),
					new SqlParameter("@RoleId", SqlDbType.NVarChar,1024),
					new SqlParameter("@Mobile", SqlDbType.NVarChar,64),
					new SqlParameter("@PassWord", SqlDbType.NVarChar,64),
					new SqlParameter("@Comment", SqlDbType.NVarChar,200),
					new SqlParameter("@RoleName", SqlDbType.NVarChar,100)};
            parameters[0].Value = model.Account;
            parameters[1].Value = model.Name;
            parameters[2].Value = model.Title;
            parameters[3].Value = model.RoleId;
            parameters[4].Value = model.Mobile;
            parameters[5].Value = model.PassWord;
            parameters[6].Value = model.Comment;
            parameters[7].Value = model.RoleName;

			int rows=DbHelperSQL.ExecuteSql(strSql.ToString(),parameters);
			if (rows > 0)
			{
				return true;
			}
			else
			{
				return false;
			}
		}

		/// <summary>
		/// 更新一条数据
		/// </summary>
		public bool Update(Meeting.Model.Employee model)
		{
            //更新时帐号不能修改
			StringBuilder strSql=new StringBuilder();
            strSql.Append("update Employee set ");
            strSql.Append("Name=@Name,");
            strSql.Append("Title=@Title,");
            strSql.Append("RoleId=@RoleId,");
            strSql.Append("Mobile=@Mobile,");
            strSql.Append("Comment=@Comment,");
            strSql.Append("RoleName=@RoleName");
            strSql.Append(" where Account=@Account ");
            SqlParameter[] parameters = {
					new SqlParameter("@Name", SqlDbType.NVarChar,64),
					new SqlParameter("@Title", SqlDbType.NVarChar,64),
					new SqlParameter("@RoleId", SqlDbType.NVarChar,1024),
					new SqlParameter("@Mobile", SqlDbType.NVarChar,64),
					new SqlParameter("@Comment", SqlDbType.NVarChar,200),
					new SqlParameter("@RoleName", SqlDbType.NVarChar,100),
					new SqlParameter("@Account", SqlDbType.NVarChar,64)};
            parameters[0].Value = model.Name;
            parameters[1].Value = model.Title;
            parameters[2].Value = model.RoleId;
            parameters[3].Value = model.Mobile;
            parameters[4].Value = model.Comment;
            parameters[5].Value = model.RoleName;
            parameters[6].Value = model.Account;

			int rows=DbHelperSQL.ExecuteSql(strSql.ToString(),parameters);
			if (rows > 0)
			{
				return true;
			}
			else
			{
				return false;
			}
		}

		/// <summary>
		/// 删除一条数据
		/// </summary>
		public bool Delete(string Account)
		{			
			StringBuilder strSql=new StringBuilder();
			strSql.Append("delete from Employee ");
			strSql.Append(" where Account=@Account ");
			SqlParameter[] parameters = {
					new SqlParameter("@Account", SqlDbType.NVarChar,64)};
			parameters[0].Value = Account;

			int rows=DbHelperSQL.ExecuteSql(strSql.ToString(),parameters);
			if (rows > 0)
			{
				return true;
			}
			else
			{
				return false;
			}
		}

		/// <summary>
		/// 批量删除数据
		/// </summary>
		public bool DeleteList(string Accountlist )
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("delete from Employee ");
			strSql.Append(" where Account in ("+Accountlist + ")  ");
			int rows=DbHelperSQL.ExecuteSql(strSql.ToString());
			if (rows > 0)
			{
				return true;
			}
			else
			{
				return false;
			}
		}

		/// <summary>
		/// 得到一个对象实体
		/// </summary>
		public Meeting.Model.Employee GetModel(string Account)
		{			
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select  top 1 Account,Name,Title,RoleId,Mobile from Employee ");
			strSql.Append(" where Account=@Account ");
			SqlParameter[] parameters = {
					new SqlParameter("@Account", SqlDbType.NVarChar,64)};
			parameters[0].Value = Account;

			Meeting.Model.Employee model=new Meeting.Model.Employee();
			DataSet ds=DbHelperSQL.Query(strSql.ToString(),parameters);
			if(ds.Tables[0].Rows.Count>0)
			{
				if(ds.Tables[0].Rows[0]["Account"]!=null && ds.Tables[0].Rows[0]["Account"].ToString()!="")
				{
					model.Account=ds.Tables[0].Rows[0]["Account"].ToString();
				}
				if(ds.Tables[0].Rows[0]["Name"]!=null && ds.Tables[0].Rows[0]["Name"].ToString()!="")
				{
					model.Name=ds.Tables[0].Rows[0]["Name"].ToString();
				}
				if(ds.Tables[0].Rows[0]["Title"]!=null && ds.Tables[0].Rows[0]["Title"].ToString()!="")
				{
					model.Title=ds.Tables[0].Rows[0]["Title"].ToString();
				}
				if(ds.Tables[0].Rows[0]["RoleId"]!=null && ds.Tables[0].Rows[0]["RoleId"].ToString()!="")
				{
					model.RoleId=ds.Tables[0].Rows[0]["RoleId"].ToString();
				}
				if(ds.Tables[0].Rows[0]["Mobile"]!=null && ds.Tables[0].Rows[0]["Mobile"].ToString()!="")
				{
					model.Mobile=ds.Tables[0].Rows[0]["Mobile"].ToString();
				}
				return model;
			}
			else
			{
				return null;
			}
		}


        public string GetRole()
        {
            DataSet ds = DbHelperSQL.Query("Select * From Role");
            if (ds == null) return "";
            JsonGrid jr = new JsonGrid();
            jr.total = ds.Tables[0].Rows.Count;
            jr.rows = ds.Tables[0];
            return JsonConvert.SerializeObject(jr);
        }

		/// <summary>
		/// 获得数据列表
		/// </summary>
		public DataSet GetList(string strWhere)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select Account,Name,Title,RoleId,Mobile,PassWord,Comment");
			strSql.Append(" FROM Employee ");
			if(strWhere.Trim()!="")
			{
				strSql.Append(" where "+strWhere);
			}
			return DbHelperSQL.Query(strSql.ToString());
		}

        /// <summary>
        /// 获取分页数据
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="filter"></param>
        /// <returns></returns>
        public string GetPage(int pageIndex, int pageSize, string filter)
        {
            int nAllRecord = 0, nAllPages = 0;


            DataTable dt = DbHelperSQL.GetPage(" Account ", "  *  ", " dbo.Employee   ", filter, " Account ", pageIndex, pageSize, out nAllRecord, out nAllPages);
            if (dt == null) return "";
            JsonGrid jr = new JsonGrid();
            jr.total = nAllRecord;
            jr.rows = dt;
            return JsonConvert.SerializeObject(jr);
        }

		/// <summary>
		/// 获得前几行数据
		/// </summary>
		public DataSet GetList(int Top,string strWhere,string filedOrder)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select ");
			if(Top>0)
			{
				strSql.Append(" top "+Top.ToString());
			}
			strSql.Append(" Account,Name,Title,RoleId,Mobile ");
			strSql.Append(" FROM Employee ");
			if(strWhere.Trim()!="")
			{
				strSql.Append(" where "+strWhere);
			}
			strSql.Append(" order by " + filedOrder);
			return DbHelperSQL.Query(strSql.ToString());
		}	
	
        #endregion
    }

    public class OaUser
    {
        public string account = "";
        public string name = "";
        public string title = "";
        public string parent = "";
        public string nodetype = "";
        public string roleId = "";
        public string roleName = "";
        public string mobile = "";

    }
}
